package com.gitee.srurl.core.util;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gitee.srurl.core.constant.GlobalConstant;
import lombok.Data;

import java.io.Serial;
import java.io.Serializable;
import java.util.Locale;

/**
 * 分页查询实体类
 *
 * @author zxw
 * @date 2023/5/3 10:40
 */
@Data
public class PageQuery implements Serializable {

    @Serial
    private static final long serialVersionUID = -5073454128884851172L;

    /**
     * 分页大小
     */
    private Integer pageSize;

    /**
     * 当前页数
     */
    private Integer pageNum;

    /**
     * 排序列
     */
    private String orderByColumn;

    /**
     * 排序的方向desc或者asc
     */
    private String isAsc;

    /**
     * 当前记录起始索引 默认值
     */
    public static final int DEFAULT_PAGE_NUM = GlobalConstant.Page.DEFAULT_PAGE_NUM;

    /**
     * 每页显示记录数 默认值 默认查全部
     */
    public static final int DEFAULT_PAGE_SIZE = GlobalConstant.Page.DEFAULT_PAGE_SIZE;

    public <T> Page<T> build() {

        Integer pageSize = ObjectUtil.defaultIfNull(getPageSize(), DEFAULT_PAGE_SIZE);
        if (pageSize < -1) {
            // 小于 -1 查询默认条
            pageSize = DEFAULT_PAGE_SIZE;
        } else if (pageSize == -1) {
            // -1 的话查询全部
            pageSize = Integer.MAX_VALUE;
        }

        Integer pageNum = ObjectUtil.defaultIfNull(getPageNum(), DEFAULT_PAGE_NUM);
        if (pageNum <= 0) {
            pageNum = DEFAULT_PAGE_NUM;
        }
        Page<T> page = new Page<>(pageNum, pageSize);
        OrderItem orderItem = buildOrderItem();
        if (ObjectUtil.isNotNull(orderItem)) {
            page.addOrder(orderItem);
        }
        return page;
    }

    private OrderItem buildOrderItem() {
        if (StrUtil.isNotBlank(orderByColumn)) {
            String orderBy = SqlUtil.escapeOrderBySql(orderByColumn);
            orderBy = orderBy.toUpperCase(Locale.ROOT);
            if ("asc".equals(isAsc)) {
                return OrderItem.asc(orderBy);
            } else if ("desc".equals(isAsc)) {
                return OrderItem.desc(orderBy);
            }
        }
        return null;
    }
}
